Skip to content

Let users save named dynamics through /v2/user-dynamics - #4337

Draft
anth-volk wants to merge 9 commits into
masterfrom
v2plan/c1-43-user-dynamics
Draft

anth-volk wants to merge 9 commits into
masterfrom
v2plan/c1-43-user-dynamics

Conversation

@anth-volk

@anth-volk anth-volk commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #4336

Summary

Users save named dynamics, as they save named policies. user_dynamics is built like user_policies without its v1 reference, baseline and provenance: the owner (a signed-in user or a signed-out browser), the country, a dynamic stored in that country, and a name and description.

  • Revision d417fe8b1b17 (parent 9d1d12a7ac58, Store dynamics like policies, create them through /v2/dynamics, and keep gov.simulation parameters out of policies #4325's revision) creates user_dynamics and nothing else. It is autogenerated, with its ID chosen through --rev-id so the tests written first could name it, and has no corrections apart from ruff format.
    • Keys: the owner's key is ON DELETE CASCADE, and the dynamic's key, with the country, is RESTRICT. So a saved dynamic names a dynamic of its own country, and that dynamic can't be deleted while it's saved.
    • Unique rule: (id, country_id) is unique. There's no unique rule on the owner and dynamic, as for saved policies.
  • Routes: POST /v2/user-dynamics (201; 404 for an unknown dynamic, 400 for another country's), GET /v2/user-dynamics (filtered by dynamic_id, paged), and GET, PATCH (rename, or repoint to another dynamic of the country) and DELETE on /v2/user-dynamics/{association_id}. They have the same credential and ownership rules as /v2/user-policies, and another user's saved dynamic answers 404.
  • Grants: the runtime role reads and writes user_dynamics, as it does user_policies; no other role has access.
  • Treated like the other saved items:
    • the sign-in merge moves a browser's saved dynamics to the account;
    • they're deleted with their user;
    • GET /v2/me/export and GET /v2/admin/users/{user_id}/saved-items list them in a new dynamics field;
    • the request log records their Supabase reads and writes.
  • For the one-time migration: it calls services.v2.user_dynamics.services.create_user_dynamic_in_session to give a v1 saved policy a saved dynamic.
  • No v1 copy: API v1 no longer writes v1 saved policies (their routes were removed on 2026-10-22), so no v1-to-v2 copy creates saved dynamics. The one-time migration creates them for existing rows.
  • File split: the saved-item service protocols move unchanged to fastapi_routes/saved_item_service_protocols.py, which resource_service_protocols re-exports, keeping that file under 800 lines.

Migration contract:

  • Routes: the new /v2/user-dynamics routes are in the policy route group, with contract user_dynamic_associations_v2.
  • Changed response: the export gains result.dynamics; nothing else changes.
  • Documents: the contract documents are regenerated.

Base and conflicts:

Testing

Tests were written first and committed failing, then the code, then three review rounds whose bugs were each fixed test-first. Each test was run by node ID:

  • SQLite service tests:
    • ownership by a signed-in user and by a browser, and that another user or browser can't read, change or delete a saved dynamic;
    • another country's dynamic and an unknown dynamic;
    • rename, repoint, paging and the filter by dynamic;
    • the RESTRICT key, deletion with the user, the sign-in merge and the export;
    • the migration function.
  • Route tests: the response shapes, refused fields and queries, error mapping and OpenAPI, plus the saved-dynamic cases of the route authentication, write-size and request-log tests.
  • Grants and registries: the grant manifest, the route group, the contract registry and documents, the revision chain, and the model tests.
  • Postgres 17:
    • the revision adds only user_dynamics, with its keys, deletion with the user, and the downgrade;
    • the runtime role saves, renames, merges at sign-in and deletes saved dynamics.
  • Checks: ruff, ruff format, lint-imports, mypy, scripts.rules validate, run_quality_guards.py, alembic -c alembic-v2.ini check, and reconcile_v2_privileges.py apply --create-missing-roles and verify.
  • CI: .github/scripts/test_alembic_v2_lifecycle.sh now runs the new revision test. alembic-v2-check.yml's postgres-lifecycle job sets the two variables it reads, V2_MIGRATION_DATABASE_URL and V2_ALEMBIC_DISPOSABLE_TEST, as literal values for its Postgres service container.

🤖 Generated with Claude Code

anth-volk and others added 7 commits November 19, 2026 20:59
Add tests for `user_dynamics`, which holds users' named saved dynamics,
built like `user_policies` without its v1 reference:

- the service: the owner is the signed-in user or the browser, and
  nobody else can read, change or delete it; the dynamic must be
  stored in the saved dynamic's own country; renaming, repointing,
  paging and filtering by dynamic; the dynamic can't be deleted while
  saved; the saved dynamic is deleted with its user, moves to the
  account at sign-in, and appears in the account export; and the
  function D4 · 1's migration calls;
- the /v2/user-dynamics routes, their error mapping and OpenAPI, and
  the routes' refusal without a credential;
- the export's new `dynamics` list in /v2/me/export and the admin
  saved-items read;
- the runtime role's grant, the `policy` route group, the contract
  registry, and the revision chain with revision d417fe8b1b17;
- against Postgres: a revision that adds only `user_dynamics`, its
  keys, deletion with the user and the downgrade, and the runtime role
  saving, merging and deleting saved dynamics.

They fail because `user_dynamics`, its services and routes, and the
revision don't exist yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add `user_dynamics`, users' named saved dynamics, built like
`user_policies` without its v1 reference, `baseline` and `provenance`:
the owner (a signed-in user or a signed-out browser), the country, a
dynamic stored in that country, and a name and description. Revision
d417fe8b1b17, on 9d1d12a7ac58, creates the table, autogenerated with
its ID chosen through --rev-id. The owner's key is ON DELETE CASCADE,
and the dynamic's key, with the country, is RESTRICT, so a saved
dynamic names a dynamic of its own country and that dynamic can't be
deleted while saved. The runtime role reads and writes it, as it does
`user_policies`.

- services/v2/user_dynamics creates, reads, lists, renames, repoints
  and deletes the caller's saved dynamics. Another user's answers 404,
  an unknown dynamic 404 and another country's 400.
  create_user_dynamic_in_session is the function D4 · 1's migration
  calls to give a v1 saved policy a saved dynamic.
- POST, GET, PATCH and DELETE /v2/user-dynamics, with the routes'
  service protocol, dependency and error mapping. The saved-item
  protocols move to fastapi_routes/saved_item_service_protocols.py,
  which resource_service_protocols re-exports, to keep that file under
  800 lines.
- The sign-in merge moves a browser's saved dynamics to the account,
  and /v2/me/export and the admin saved-items read list them in
  `dynamics`.
- `user-dynamics` joins the policy route group. The contract registry
  gains user_dynamic_associations_v2 and the export's
  `result.dynamics`, and the contract documents are regenerated.
- The revision's integration test runs in the v2 lifecycle CI script.

v1's saved-policy copy is unchanged: v1 no longer writes saved
policies, so D4 · 1's migration creates saved dynamics for existing
ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review round 1 found that the request log records /v2/user-dynamics
with the policy route group's Cloud SQL database settings, because the
logging module's lists of Supabase and saved-work route segments omit
`user-dynamics`. Add its GET, POST, PATCH and DELETE to the cases that
must log Supabase reads or writes and no simulation flow, and set the
policy group's database settings to invalid values there, as the other
groups' are, so a case that reads them fails.

They fail with migration_flag_error from DB_WRITE_POLICY.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add `user-dynamics` to the logging module's Supabase resources and
saved-work routes, as `user-policies` is, so its requests record
Supabase reads or writes and no simulation flow instead of the policy
route group's configured v1 database settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
From review round 1's code-quality findings:

- The contract test that requires every saved-item route to accept a
  signed-out browser's header now checks /v2/user-dynamics too.
- The Stage 12A document lists /v2/user-dynamics among the saved-item
  routes and saved dynamics in the admin saved-items read.
- The typing-only imports skill names user_dynamics among the route
  modules that don't use `from __future__ import annotations`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review round 2 found three existing tests that saved dynamics broke,
each seen failing by node ID before this change:

- test_openapi_references_explicit_resource_response_schemas lists
  every native v2 path; it now includes /v2/user-dynamics.
- test_migration_contract_payload_summarizes_route_contracts pins the
  contract counts and names; it now has 20 workflows and 113 requests,
  with user_dynamic_associations_v2.
- The dynamics revision's downgrade-refusal test upgraded to its own
  revision, which does nothing from a newer head, so the refused
  downgrade also ran this revision's step, rolled both back and left
  the newer version recorded. It now steps down to its revision first.
  The saved-dynamics downgrade test does the same, so a later revision
  doesn't break it.

Round 2's code-quality findings:

- The write-size test injects a saved-dynamic service, so its check
  that no service ran covers /v2/user-dynamics.
- The model tests check saved dynamics' country key, module and owner
  key with the other saved items.
- The countries model's docstring and the Stage 12A document count
  dynamics and saved dynamics.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Review round 3 found that the import side-effect test pins the number
of v2 tables at 50; `user_dynamics` makes it 51. It failed at that
assertion when run by node ID before this change.

Round 3's code-quality findings:

- The check that user services build no SQL now covers the
  saved-dynamic service, as rule api.v2.user-services-no-sql says.
- The revision CI check requires the saved-dynamics revision test in
  the Postgres revision test script.
- The country-key model test covers `dynamics.country_id`, which the
  countries model's docstring names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.00000% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.66%. Comparing base (80a42dd) to head (f1ecc00).

Files with missing lines Patch % Lines
policyengine_api/fastapi_routes/dependencies.py 33.33% 4 Missing ⚠️
..._api/services/v2/user_dynamics/database_session.py 85.71% 2 Missing ⚠️
...fastapi_routes/v2/user_dynamics/response_models.py 97.43% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #4337      +/-   ##
==========================================
+ Coverage   93.63%   93.66%   +0.03%     
==========================================
  Files         408      421      +13     
  Lines       23282    23605     +323     
  Branches     3648     3683      +35     
==========================================
+ Hits        21799    22110     +311     
- Misses        868      880      +12     
  Partials      615      615              
Flag Coverage Δ
integration 58.10% <81.42%> (+0.30%) ⬆️
unit 91.02% <98.00%> (+0.07%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Base automatically changed from v2plan/c1-36-dynamics to master November 19, 2026 20:56
test_user_contracts_require_a_signed_in_or_signed_out_credential pins
how many user-route contract requests take each credential. The five
/v2/user-dynamics operations add one of each per header, so there are
now 31 with a bearer token and 28 with the unauthenticated-user header.
CI's test shard 3 reported it failing, and it failed the same way when
run by node ID.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Let users save named dynamics through /v2/user-dynamics

1 participant